#include "datatransfer.h"
#include <QDataStream>
#include <QDebug>

DataTransfer::DataTransfer(QObject *parent) :
    QObject(parent)
{
    inProgress = false;
    blockSize = 1024;
}

void DataTransfer::send(QIODevice *from, QAbstractSocket *to)
{
    if(inProgress)
    {
        qDebug() << "DataTransfer is busy";
        return;
    }
    if(!from->isReadable())
    {
        qDebug() << "can't read data from: " << from;
        return;
    }
    if(!to->isWritable())
    {
        qDebug() << "can't write data to: " << to;
        return;
    }

    QDataStream read(from);
    qint64 readBytes = 0;
    char *buf = new char[blockSize];
    buf[blockSize-1] = '\0';
    inProgress = true;
    emit sendBegin();
    while(!read.atEnd())
    {
      int realyRead = read.readRawData(buf, sizeof(char)*blockSize);
      qDebug() << "read bytes: " << realyRead;
      int sendBytes = to->write(buf, realyRead);
      if (sendBytes == -1)
      {
        qDebug() << "error while send data";
        inProgress = false;
        emit sendEnd(true);
        return;
      }
      readBytes += sendBytes;
      qDebug() << "send " << sendBytes << "/" << readBytes;
    }
    emit sendEnd(false);
    inProgress = false;
}

bool DataTransfer::isProgress()
{
    return inProgress;
}
